package com.superyee.commonlib.logic;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qiniu.android.http.ResponseInfo;
import com.superyee.commonlib.constants.UrlConstants;
import com.superyee.commonlib.entity.AttachFileBean;
import com.superyee.commonlib.http.OkHttpClientManager;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.exceptions.Exceptions;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 七牛文件上传公共类
 */
public class AppUploadManager extends BaseLogic<String> {

    private com.qiniu.android.storage.UploadManager mUploadManager;
    private Context mContext;

    public AppUploadManager(Context context) {
        mContext = context.getApplicationContext();
    }


    /**
     * 上传文件
     *
     * @param tokenType 七牛token类型
     *                  [common]	公共bucket token
     *                  [moment]	朋友圈bucket token
     * @param fileList
     */
    public Observable<AttachFileBean[]> uploadFile(String tokenType, final List<AttachFileBean> fileList) {
        return getToken(tokenType).flatMap((Function<String, Observable<AttachFileBean[]>>) token -> {
            Observable<AttachFileBean>[] uploadArr = new Observable[fileList.size()];
            for (int i = 0; i < fileList.size(); i++) {
                uploadArr[i] = createUploadObservable(token, fileList.get(i));
            }
            //批量上传到七牛
            return Observable.zipArray(list -> {
                if (list == null) {
                    return new AttachFileBean[0];
                } else {
                    AttachFileBean[] result = new AttachFileBean[list.length];
                    for (int i = 0; i < result.length; i++) {
                        result[i] = (AttachFileBean) list[i];
                    }
                    return result;
                }
            }, true, 2, uploadArr);
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
//                .subscribe(new Consumer<String[]>() {
//                    @Override
//                    public void accept(AttachFileBean[] uploadResult) throws Exception {
//                        上传成功
//                    }
//                }, new Consumer<Throwable>() {
//                    @Override
//                    public void accept(Throwable throwable) throws Exception {
//                        ObserverManager.getInstence().notifyUi(action, throwable == null ? "上传失败" : throwable.getMessage(), ObserverManager.FAILURE);
//                    }
//                });
    }

    /**
     * 构造文件上传
     *
     * @param token
     * @param file
     * @return
     */
    private Observable<AttachFileBean> createUploadObservable(final String token, AttachFileBean file) {
        Observable<AttachFileBean> observable = Observable.just(file).map(uploadFile -> {
            if (!uploadFile.isVideo && !TextUtils.isEmpty(uploadFile.localPath)) {
                try {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(uploadFile.localPath, options);
                    uploadFile.width = options.outWidth;
                    uploadFile.height = options.outHeight;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (uploadFile.uploaded || TextUtils.isEmpty(uploadFile.localPath)) {
                return uploadFile;
            }
            //上传文件到七牛
            ResponseInfo responseInfo = getUploadManager().syncPut(uploadFile.localPath, uploadFile.path, token, null);
            if (responseInfo != null && responseInfo.isOK()) {
                uploadFile.uploaded = true;
            } else {
                uploadFile.uploaded = false;
                Exceptions.propagate(new Throwable(responseInfo == null ? "上传失败" : responseInfo.error));
            }
            return uploadFile;
        }).subscribeOn(Schedulers.newThread());
        return observable;
    }


    private synchronized com.qiniu.android.storage.UploadManager getUploadManager() {
        if (mUploadManager == null) {
            mUploadManager = new com.qiniu.android.storage.UploadManager();
        }
        return mUploadManager;
    }

    /**
     * 获取七牛上传凭证
     *
     * @return
     */
    private Observable<String> getToken(final String type) {
        return Observable.create(emitter -> {
            String response = OkHttpClientManager.getAsString(mContext, UrlConstants.URL_QINIU_TOKEN + "?type=" + type);
            String token = null;
            if (response != null) {
                JSONObject json = JSON.parseObject(response);
                token = json.getString("token");
            }
            if (TextUtils.isEmpty(token)) {
                emitter.onError(new Throwable(response == null ? "获取七牛token失败" : getError(response)));
                Exceptions.propagate(new Throwable(response == null ? "获取七牛token失败!!" : getError(response)));
            }
            emitter.onNext(token);
            emitter.onComplete();
        });
    }


    @Override
    protected void success(int statusCode, int action, String result, Object obj) {

    }
}
